<template>
  <div style="margin: 0 20px;">
    <div style="margin: 0 0 15px 0; padding: 10px 20px;border: 1px solid #ccc; border-radius: 3px; background: #efeeee; color: #666;">
      <p style="margin: 0; padding: 0;">提示：本页用于演示沙箱支付，每单只取购物车中的某1样商品，固定使用ID=1的收货地址，请确保此收货地址属于当前登录的用户</p>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="goodsId" label="ID" width="60"/>
      <el-table-column prop="goodsTitle" label="标题" :show-overflow-tooltip="true"/>
      <el-table-column prop="goodsBrief" label="简介" width="300" :show-overflow-tooltip="true"/>
      <el-table-column prop="goodsSalePrice" label="价格" width="100"/>
      <el-table-column prop="goodsIsPutOn" label="是否上架" width="100"/>
      <el-table-column prop="goodsNum" label="数量" width="100"/>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini"
                     @click="createOrder(scope.row)">下单
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginInfo: {
        token: ''
      },
      cartListUrl: 'http://localhost:19282/carts',
      createOrderUrl: 'http://localhost:19282/orders/create',
      receiverAddressId: 1,
      tableData: []
    }
  },
  methods: {
    loadLoginInfo() {
      let loginInfoString = localStorage.getItem('alipay_loginInfo');
      if (!loginInfoString) {
        this.$alert('请先登录！', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.push('/alipay/login');
            return;
          }
        });
      }
      this.loginInfo = JSON.parse(loginInfoString);
    },
    createOrder(cart) {
      let params = 'receiverAddressId=' + this.receiverAddressId + '&goodsIdList=' + cart.goodsId;
      this.axios
          .create({'headers': {'Authorization': this.loginInfo.token}})
          .post(this.createOrderUrl, params).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            message: '创建订单成功！',
            type: 'success'
          });
        } else {
          this.$message.error(jsonResult.message);
        }
      });
    },
    loadCartList() {
      this.axios
          .create({'headers': {'Authorization': this.loginInfo.token}})
          .get(this.cartListUrl).then((response) => {
        this.tableData = response.data.data;
      });
    }
  },
  created() {
    this.loadLoginInfo();
  },
  mounted() {
    this.loadCartList();
  }
}
</script>